package com.well.gateway.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * test
 * </p>
 *
 * @author weedo
 * @since 2022/12/4
 */

@Controller
public class TestController {
    @Resource
    private RestTemplate restTemplate;

    // response添加header
    public void addRequestHeader(HttpServletResponse response, HttpHeaders headers) {
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            String headerName = entry.getKey();
            List<String> headValues = entry.getValue();
            for (String headValue : headValues) {
                response.addHeader(headerName, headValue);
            }
        }
    }

    // response添加header
    public void addHeader(HttpServletResponse response, HttpHeaders headers) {
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            String headerName = entry.getKey();
            List<String> headValues = entry.getValue();
            for (String headValue : headValues) {
                response.addHeader(headerName, headValue);
            }
        }
    }

    public byte[] createRequestBody(HttpServletRequest request) throws IOException {
        InputStream inputStream = request.getInputStream();
        //作用
        return StreamUtils.copyToByteArray(inputStream);
    }
    private RequestEntity createRequestEntity(HttpServletRequest request, String url) throws IOException, URISyntaxException {
        String method = request.getMethod();
        HttpMethod httpMethod = HttpMethod.resolve(method);
        //1.封装请求头
        MultiValueMap<String, String> headers = createRequestHeaders(request);
        byte[] body = createRequestBody(request);
        //3.构造出RestTemplate能识别的RequestEntity
        RequestEntity requestEntity = new RequestEntity<byte[]>(body, headers, httpMethod, new URI(url));
        return requestEntity;
    }


    public MultiValueMap<String, String> createRequestHeaders(HttpServletRequest request) {
        HttpHeaders headers = new HttpHeaders();
        List<String> headerNames = Collections.list(request.getHeaderNames());
        for (String headerName : headerNames) {
            List<String> headerValues = Collections.list(request.getHeaders(headerName));
            for (String headreValue : headerValues) {
                headers.add(headerName, headreValue);
            }
        }
        return headers;
    }

    public String getUrl(HttpServletRequest request) {
        String method = request.getMethod();
        StringBuffer url = new StringBuffer();
        if (method.equals(HttpMethod.GET.name())) {
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (Map.Entry entry: parameterMap.entrySet()) {
                try {
                    String value = URLEncoder.encode(((String[]) entry.getValue())[0], "utf-8");
                    url.append("&");
                    url.append(entry.getKey());
                    url.append("=");
                    url.append(value);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            url.toString().replaceFirst("&", "");
        }
        if (!StringUtils.isEmpty(url.toString())) {
            return request.getRequestURI() + "?" + url.toString();
        }
        return request.getRequestURI();
    }

    @ResponseBody
    @RequestMapping("/**")
    void test(HttpServletRequest request, HttpServletResponse response) throws IOException, URISyntaxException {
        ResponseEntity<byte[]> responseEntity = restTemplate.exchange(createRequestEntity(request, "https://www.baidu.com" + getUrl(request)), byte[].class);
        response.setCharacterEncoding("UTF-8");
        addHeader(response, responseEntity.getHeaders());
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] body = responseEntity.getBody();
        if (body != null) {
            outputStream.write(body);
            outputStream.flush();
        }
        System.out.println(request.getRequestURI());
    }
}
